package zh.dummy.netty.core.codec;

import java.io.UnsupportedEncodingException;
import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;

public class FastjsonEncoder {
	
	protected void encodeHeaderAttch(Object msg,ByteBuf out){
		if(out == null){
			return;
		}
		int writerIndex = out.writerIndex();
		out.writeInt(0);
		if(msg == null){
			return;
		}
		String jsonMsg = JSON.toJSONString(msg);
		byte[] msgBytes = null;
		try {
			msgBytes = jsonMsg.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		out.writeBytes(msgBytes);
		out.setInt(writerIndex, msgBytes.length);
	}
	
	protected void encodeBody(Object msg,ByteBuf out) {
		if(msg == null || out == null){
			return;
		}
		String jsonMsg = JSON.toJSONString(msg);
		byte[] msgBytes = null;
		try {
			msgBytes = jsonMsg.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		out.writeBytes(msgBytes);
	}
}
